package com.oraycn.esbasic.helpers;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.widget.Toast;

import com.blankj.utilcode.util.FileUtils;
import com.oraycn.esbasic.models.BasicResultType;
import com.oraycn.esbasic.models.FileType;
import com.oraycn.esbasic.utils.FileUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

public class FileHelper {

    public static final int SELECT_IMG = 100;
    public static final int SELECT_FILE = 200;

    /**
     * 系统方式打开文件
     *
     * @param file
     */
    public static boolean openFile(Context context,File file) {
        try {
            //Uri uri = Uri.parse("file://"+file.getAbsolutePath());
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //设置intent的Action属性
            intent.setAction(Intent.ACTION_VIEW);
            //获取文件file的MIME类型
            String type = getMIMEType(file);
            //设置intent的data和Type属性。
//            intent.setDataAndType(Uri.fromFile(file), type);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", file);//第二个参数要和Mainfest中<provider>内的android:authorities 保持一致
                intent.setDataAndType(uri, type);
            } else {
                intent.setDataAndType(Uri.fromFile(file), type);
            }

            //跳转
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void openFileByWps(Context context,File file){
        Intent intent = new Intent();

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setClassName("cn.wps.moffice", "cn.wps.moffice.documentmanager.PreStartActivity");
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.startActivity(intent);
    }


    /// <summary>
    /// 拷贝图片到本地缓存目录
    /// </summary>
    /// <param name="oldImagePath"></param>
    /// <returns>返回本地缓存路径中的该图片</returns>
    public static void copyFile(String oldFilePath,String destFilePath) {
        try {
            if (StringHelper.isNullOrEmpty(oldFilePath)) {
                return ;
            }

            Path oldPath = null;
            Path destPath = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                oldPath = new File(oldFilePath).toPath();
                destPath = new File(destFilePath).toPath();
                Files.copy(oldPath, destPath, StandardCopyOption.REPLACE_EXISTING);//复制该图片到本地缓存目录
            }
        } catch (Exception e) {

        }
    }

    /**
     * 获取链接文件的二进制数据
     * @param urlStr 文件远程链接
     * @return
     * @throws Exception
     */
    public static byte[] readFileURLReturnBytes(String urlStr)throws Exception
    {
        BufferedInputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            if (StringHelper.isNullOrEmpty(urlStr)) {
                return  null;
            }
            URL url = new URL(urlStr);
            HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            inputStream = new BufferedInputStream(httpUrl.getInputStream());
            outputStream = new ByteArrayOutputStream();
            int i = inputStream.available();
            byte[] datas = new byte[i];
            int len = 0;
            while ((len = inputStream.read(datas)) != -1) {
                outputStream.write(datas, 0, len);
            }
            return outputStream.toByteArray();
        } catch (Exception ex) {
            throw ex;
        } finally {
            try {
                if (outputStream!=null) {
                    outputStream.close();
                }
                if (inputStream!=null) {
                    inputStream.close();
                }
            } catch (IOException ex) {

            }
        }
    }

    /**
     * 读取InputStream流中的byte[]数据
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inputStream)throws Exception
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int i = inputStream.available();
        byte[] datas = new byte[i];
        int len = 0;
        while ((len = inputStream.read(datas)) != -1) {
            outputStream.write(datas, 0, len);
        }
        byte[] buff=outputStream.toByteArray();
        outputStream.close();
        inputStream.close();
        return buff;
    }

    /**
     * 获取远程链接文件大小
     * @param urlStr
     * @return
     * @throws Exception
     */
    public static long getUrlFileSize(String urlStr)throws Exception
    {
        URL url = new URL(urlStr);
        URLConnection uc = url.openConnection();
        return uc.getContentLength();
    }

    /**
     * 获取远程链接文件名称（可以是中文）
     * @param urlStr
     * @return
     * @throws Exception
     */
    public static String getUrlFileName(String urlStr)throws Exception
    {
       String shareUrl=  URLDecoder.decode(urlStr,"UTF-8");
        shareUrl = shareUrl.split("[?]")[0];
        String[] strs = shareUrl.split("/");
        return getFileNameNoPath(strs[strs.length - 1]);
    }

    /**
     * 读取本地文件 二进制
     * @param path 本地地址
     * @return
     */
    public static byte[] readFileToByteArray(String path) {
        File file = new File(path);
        if(!file.exists()) {

            return null;
        }
        FileInputStream in=null;
        try {
            in = new FileInputStream(file);
            long inSize = in.getChannel().size();//判断FileInputStream中是否有内容
            if (inSize == 0) {

                return null;
            }

            byte[] buffer = new byte[in.available()];//in.available() 表示要读取的文件中的数据长度
            in.read(buffer);  //将文件中的数据读到buffer中
            return buffer;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                return null;
            }
            //或IoUtils.closeQuietly(in);
        }
    }


    /**
     * 获取文件的MIME
     * @param file
     * @return
     */
    private static String getMIMEType(File file)
    {
        if(file==null){return null;}
        String fileName=file.getName();
        String suffix=   fileName.substring(fileName.lastIndexOf("."));
        for (String[] strs :MIME_MapTable) {
            if(strs[0].equals(suffix))
            {
                return strs[1];
            }
        }
        return null;
    }

    //建立一个MIME类型与文件后缀名的匹配表
    private static final String[][] MIME_MapTable={
            //{后缀名，    MIME类型}
            {".3gp",    "video/3gpp"},
            {".apk",    "application/vnd.android.package-archive"},
            {".asf",    "video/x-ms-asf"},
            {".avi",    "video/x-msvideo"},
            {".bin",    "application/octet-stream"},
            {".bmp",      "image/bmp"},
            {".c",        "text/plain"},
            {".class",    "application/octet-stream"},
            {".conf",    "text/plain"},
            {".cpp",    "text/plain"},
            {".doc",    "application/msword"},
            {".docx",    "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".exe",    "application/octet-stream"},
            {".gif",    "image/gif"},
            {".gtar",    "application/x-gtar"},
            {".gz",        "application/x-gzip"},
            {".h",        "text/plain"},
            {".htm",    "text/html"},
            {".html",    "text/html"},
            {".jar",    "application/java-archive"},
            {".java",    "text/plain"},
            {".jpeg",    "image/jpeg"},
            {".jpg",    "image/jpeg"},
            {".js",        "application/x-javascript"},
            {".log",    "text/plain"},
            {".m3u",    "audio/x-mpegurl"},
            {".m4a",    "audio/mp4a-latm"},
            {".m4b",    "audio/mp4a-latm"},
            {".m4p",    "audio/mp4a-latm"},
            {".m4u",    "video/vnd.mpegurl"},
            {".m4v",    "video/x-m4v"},
            {".mov",    "video/quicktime"},
            {".mp2",    "audio/x-mpeg"},
            {".mp3",    "audio/x-mpeg"},
            {".mp4",    "video/mp4"},
            {".mpc",    "application/vnd.mpohun.certificate"},
            {".mpe",    "video/mpeg"},
            {".mpeg",    "video/mpeg"},
            {".mpg",    "video/mpeg"},
            {".mpg4",    "video/mp4"},
            {".mpga",    "audio/mpeg"},
            {".msg",    "application/vnd.ms-outlook"},
            {".ogg",    "audio/ogg"},
            {".pdf",    "application/pdf"},
            {".png",    "image/png"},
            {".pps",    "application/vnd.ms-powerpoint"},
            {".ppt",    "application/vnd.ms-powerpoint"},
            {".pptx",    "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {".prop",    "text/plain"},
            {".rar",    "application/x-rar-compressed"},
            {".rc",        "text/plain"},
            {".rmvb",    "audio/x-pn-realaudio"},
            {".rtf",    "application/rtf"},
            {".sh",        "text/plain"},
            {".swf",        "application/x-shockwave-flash"},
            {".tar",    "application/x-tar"},
            {".tgz",    "application/x-compressed"},
            {".txt",    "text/plain"},
            {".wav",    "audio/x-wav"},
            {".wma",    "audio/x-ms-wma"},
            {".wmv",    "audio/x-ms-wmv"},
            {".wps",    "application/vnd.ms-works"},
            {".xls",    "application/vnd.ms-excel application/x-excel"},
            {".xlsx",    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            //{".xml",    "text/xml"},
            {".xml",    "text/plain"},
            {".z",      "application/x-compress"},
            {".zip",    "application/x-zip-compressed"},
            {"",        "*/*"}
    };

    /**
     * 打开相册
     *
     * @param activity 活动对象
     */
    public static void openPhotoAlbum(Activity activity) {
        //解决小米某些机型打开相册出错的问题
        Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//        intent.setType("image/*");
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            activity.startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的图片"), SELECT_IMG);
        } catch (android.content.ActivityNotFoundException ex) {
            ToastHelper.showShort(activity.getApplication(), "请安装文件管理器");
        }
    }

    /**
     * 打开文件选择器
     *
     * @param activity 活动对象
     */
    public static void openFileSelector(Activity activity) {
        Intent intentFile = new Intent(Intent.ACTION_GET_CONTENT);
        intentFile.setType("*/*");
        intentFile.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            activity.startActivityForResult(Intent.createChooser(intentFile, "请选择一个要上传的文件"), SELECT_FILE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(activity, "", Toast.LENGTH_SHORT).show();
            ToastHelper.showShort(activity, "请安装文件管理器");
        }
    }

    /**
     * 保存二进制到本地
     * @param data
     * @param filePath
     * @return
     */
    public static BasicResultType saveByteArrayToFile(byte[] data,String filePath)
    {
        String fileCatalogPath=getFileDirectory(filePath);
        File path = new File(fileCatalogPath);
        if (!path.exists()) {
            path.mkdirs();
        }
        File file = new File(fileCatalogPath, getFileNameNoPath(filePath));
        // 创建FileOutputStream对象
        FileOutputStream outputStream = null;
        // 创建BufferedOutputStream对象
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 如果文件存在则删除
            if (file.exists()) {
                file.delete();
            }
            // 在文件系统中根据路径创建一个新的空文件
            file.createNewFile();
            // 获取FileOutputStream对象
            outputStream = new FileOutputStream(file);
            // 获取BufferedOutputStream对象
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            // 往文件所在的缓冲输出流中写byte数据
            bufferedOutputStream.write(data);
            // 刷出缓冲输出流，该步很关键，要是不执行flush()方法，那么文件的内容是空的。
            bufferedOutputStream.flush();
            return BasicResultType.Succeed;
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
        } finally {
            // 关闭创建的流对象
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
        return BasicResultType.Error;
    }

    /**
     * 将字符串写入到文件
     * @param lines
     * @param filePath
     * @return
     */
    public static BasicResultType saveAllLinesToFile(List<String> lines,String filePath) {
        ensureDirectoryExist(filePath);
        FileWriter fw = null;
        try {
            fw = new FileWriter(filePath);
            for (int i = 0; i < lines.size(); i++) {
                fw.write(lines.get(i)+"\n");
            }
            fw.flush();
            fw.close();
            return BasicResultType.Succeed;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return BasicResultType.Error;
    }

    /**
     * 保存图片到系统相册
     *
     * @param context
     * @param bmp     图片
     * @param picName 保存的图片名称
     */
    public static void saveBitmapToDCIM(Context context, Bitmap bmp, String picName) {
        String fileName = null;
        //系统相册目录
        String galleryPath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;

        // 声明文件对象
        File file = null;
        // 声明输出流
        FileOutputStream outStream = null;
        try {
            // 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
            file = new File(galleryPath, picName + ".jpg");

            // 获得文件相对路径
            fileName = file.toString();
            // 获得输出流，如果文件中有内容，追加内容
            outStream = new FileOutputStream(fileName);
            if (null != outStream) {
                bmp.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
            }

        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //通知相册更新
        MediaStore.Images.Media.insertImage(context.getContentResolver(),
                bmp, fileName, null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);
        ToastHelper.showShort(context, "图片已保存到相册");
    }


    /**
     * 将图片保存到本地
     *
     * @param mBitmap  图片
     * @param filePath 要保存完整的路径(包含图片名称)，
     * @return BasicResultType (成功、失败)
     */
    public static BasicResultType saveBitmapToLocalPath(Bitmap mBitmap, String filePath) {
        String fileCatalogPath = filePath.substring(0, filePath.lastIndexOf("/"));
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        return FileHelper.saveBitmapToLocalPath(mBitmap, fileCatalogPath, fileName);
    }

    /**
     * 将图片保存到本地
     *
     * @param mBitmap         图片
     * @param fileCatalogPath 要保存的路径，
     * @param picName         保存的图片名称
     * @return BasicResultType (成功、失败)
     */
    public static BasicResultType saveBitmapToLocalPath(Bitmap mBitmap, String fileCatalogPath, String picName) {
        File path = new File(fileCatalogPath);
        if (!path.exists()) {
            path.mkdirs();
        }
        File f = new File(path, picName);
        try {
            f.createNewFile();
            FileOutputStream fOut = null;
            fOut = new FileOutputStream(f);
            mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            mBitmap.recycle();
            fOut.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return BasicResultType.Error;
        } catch (IOException e) {
            e.printStackTrace();
            return BasicResultType.Error;
        }
        return BasicResultType.Succeed;
    }


    /**
     * 获取文件夹下所有文件的 文件名
     * @param directoryPath 文件夹路径
     * @return
     */
    public static List<String> getAllFileNames(String directoryPath) {
        File file=new File(directoryPath);
        File[] files=file.listFiles();
        if (files == null){
            return null;}
        List<String> list = new ArrayList<>();
        for(int i =0;i<files.length;i++){
            list.add(files[i].getName());
        }
        return list;
    }

    /**
     * 获取文件夹下所有文件的绝对路径
     * @param directoryPath 文件夹路径
     * @return
     */
    public static List<String> getAllFileAbsolutePath(String directoryPath) {
        File file=new File(directoryPath);
        File[] files=file.listFiles();
        if (files == null){
            return null;}
        List<String> list = new ArrayList<>();
        for(int i =0;i<files.length;i++){
            list.add(files[i].getAbsolutePath());
        }
        return list;
    }

    /**
     * 根据文件路径获取文件名（包括后缀）
     *
     * @param filePath
     */
    public static String getFileName(String filePath) {
        return getFileName(filePath, true);
    }

    /**
     * 根据文件路径获取文件名
     *
     * @param filePath
     * @param containSuffix 是否包含后缀名
     */
    public static String getFileName(String filePath, boolean containSuffix) {
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        if (containSuffix) {
            return fileName;
        }
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    /// <summary>
    /// GetFileNameNoPath 获取不包括路径的文件名
    /// </summary>
    public static String getFileNameNoPath(String filePath)
    {
        if (filePath.contains(String.valueOf(File.separatorChar) ))
        {
            String[] ary = filePath.split(String.valueOf(File.separatorChar));
            return ary[ary.length - 1];
        }

        return filePath;
    }

    /**
     * 获取文件的扩展名（全小写）。如“.docx”，“.pdf”等
     * @param filePath
     * @return
     */
    public static String getExtendName(String filePath)
    {
        if(StringHelper.isNullOrEmpty(filePath)){return "";}
        return filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
    }



    /**
     * 获取文件所在的目录路径
     * @param filePath
     * @return
     */
    public static String getFileDirectory(String filePath)
    {
        if (filePath.contains(String.valueOf(File.separatorChar) ))
        {
            return filePath.substring(0,filePath.lastIndexOf(File.separatorChar)+1);
        }
        return filePath;
    }

    /**
     * 确保文件夹存在
     * @param filePath
     * @return
     */
    public static void ensureDirectoryExist(String filePath)
    {
        String dir=getFileDirectory(filePath);
        File file=new File(dir);
        if(!file.exists())
        {
            file.mkdirs();
        }
    }

    // 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
    @SuppressLint("NewApi")
    public static String getRealPathFromUri(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && android.os.Build.VERSION.SDK_INT < 29 && DocumentsContract.isDocumentUri(context, uri) ) {
            if (isExternalStorageDocument(uri)) {// ExternalStorageProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(uri)) {// DownloadsProvider
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {// MediaProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[] { split[1] };
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        else if(Build.VERSION.SDK_INT >= 29 ){
            return uriToFileApiQ(context,uri);
        }
        else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore
            // (and
            // general)
            return getDataColumn(context, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {// File
            return uri.getPath();
        }
        return null;
    }


    /**
     * Android 10 以上适配
     * @param context
     * @param uri
     * @return
     */
    @RequiresApi(api = 29)
    private static String uriToFileApiQ(Context context, Uri uri) {
        File file = null;
        //android10以上转换
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
            ContentResolver contentResolver = context.getContentResolver();
            Cursor cursor = contentResolver.query(uri, null, null, null, null);
            if (cursor.moveToFirst()) {
                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                try {
                    FileInputStream is = (FileInputStream)contentResolver.openInputStream(uri);
                    File cache = new File(context.getExternalCacheDir().getAbsolutePath(), Math.round((Math.random() + 1) * 1000) + displayName);
                    FileOutputStream fos = new FileOutputStream(cache);
                    FileUtil.copyFile(is, fos);
                    file = cache;
                    fos.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file.getAbsolutePath();
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context
     *            The context.
     * @param uri
     *            The Uri to query.
     * @param selection
     *            (Optional) Filter used in the query.
     * @param selectionArgs
     *            (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = { column };
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

 
    /**
     * 根据文件大小转换为B、KB、MB、GB单位字符串显示  （去掉尾数 非4舍5入）
     *
     * @param filesize 文件的大小（long型）
     * @return 返回 转换后带有单位的字符串
     */
    public static String getFileLengthString(long filesize) {
        String strFileSize = null;
        if (filesize < 1024) {
            strFileSize = filesize + "B";
            return strFileSize;
        }
        DecimalFormat df = new DecimalFormat("######0.00");
        df.setRoundingMode(RoundingMode.FLOOR);
        if ((filesize >= 1024) && (filesize < 1024 * 1024)) {//KB
            strFileSize = df.format(((double) filesize) / 1024) + "KB";
        } else if ((filesize >= 1024 * 1024) && (filesize < 1024 * 1024 * 1024)) {//MB
            strFileSize = df.format(((double) filesize) / (1024 * 1024)) + "MB";
        } else {//GB
            strFileSize = df.format(((double) filesize) / (1024 * 1024 * 1024)) + "GB";
        }
        return strFileSize;
    }

    /**
     * 获取文件类型
     * @param fileName 文件名称
     * @return
     */
    public static FileType getFileType(String fileName)
    {
        try {
            String suffix = fileName.substring(fileName.lastIndexOf('.')+1);
            switch (suffix.toLowerCase())
            {
                case "txt":
                        return FileType.Txt;
                case "xls":
                case "xlsx":
                    return FileType.Excel;
                case "doc":
                case "docx":
                    return FileType.Word;
                case "ppt":
                case "pptx":
                    return FileType.PPT;
                case "pdf":
                    return FileType.PDF;
                case "zip":
                case "rar":
                    return FileType.Rar;
                case "exe":
                    return FileType.Exe;
                case "gif":
                case "jpg":
                case "jpeg":
                case "png":
                case "bmp":
                case "ico":
                case "svg":
                case "tiff":
                    return FileType.Image;
                case "mp3":
                case "wma":
                case "wav":
                case "aif":
                case "aiff":
                case "au":
                case "ram":
                case "mid":
                case "rmi":
                return FileType.Music;
                case "mp4":
                case "avi":
                case "mov":
                case "rmvb":
                case "rm":
                case "flv":
                case "3gp":
                case "mpeg":
                case "mpg":
                case "dat":
                case "mkv":
                    return FileType.Video;
                default:
                    return FileType.Other;
            }

        }catch (Exception e)
        {
            return FileType.Other;
        }

    }

    /**
     * 判断文件是否存在
     * @param strFile
     * @return
     */
    public static boolean isExist(String strFile)
    {
        try
        {
            File f=new File(strFile);
            if(!f.exists())
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }
        return true;
    }

    /**
     * 将png图片转化为jpg图片
     * @param pngFilePath
     * @param jpgFilePath
     */
    public static void convertToJpg(String pngFilePath, String jpgFilePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(pngFilePath);
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(jpgFilePath))) {
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos)) {
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean isImgFile(String fileName)
    {
        String[] suffixNames=new String[]{".jpg",".png",".gif",".jpeg",".bmp"};
        return judgeFileName(fileName,suffixNames);
    }

    public static boolean isAudioFile(String fileName)
    {
        String[] suffixNames=new String[]{".mp3",".wma",".wav"};
        return judgeFileName(fileName,suffixNames);
    }

    /// <summary>
    /// 链接是否为网络链接
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static boolean isHttpUrl(String url)
    {
        if (StringHelper.isNullOrEmpty(url)) return false;
        return url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https");
    }

    //判断文件名称 是否在指定的后缀名中
    private static boolean judgeFileName(String fileName,String[] suffixNames)
    {
        if(StringHelper.isNullOrEmpty(fileName)){
            return false;
        }
        fileName=fileName.toLowerCase();
        for (String suffiexName:suffixNames) {
            if(fileName.contains(suffiexName))
            {
                return true;
            }
        }
        return false;
    }
}